function Promise(executor) {
    let self = this;
    this.callbacks = [];
    this.promiseState = 'pending';
    this.promiseResult = null;
    function resolve(value) {
        if (self.promiseState !== 'pending') return;
        // 1. 改变状态
        // 2. 结果值
        self.promiseState = 'fulfilled';
        self.promiseResult = value;
        self.callbacks.forEach(item => {
            item.onResolve();
        });
    }
    function reject(reason) {
        if (self.promiseState !== 'pending') return;
        self.promiseState = 'rejected';
        self.promiseResult = reason;
        self.callbacks.forEach(item => {
            item.onReject();
        });
    }
    try {
        executor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}

Promise.prototype.then = function (onResolve, onReject) {

    let self = this;
    function changeState(type){
        let rs = type(self.promiseResult);
        if (rs instanceof Promise) {
            rs.then(resolve,reject);
        } else {
            resolve(rs);
        }
    }
    return new Promise((resolve, reject) => {
        if (this.promiseState === 'fulfilled') {
            changeState('onResolve');
        }
        if (this.promiseState === 'rejected') {
            changeState('onReject');
        }
        if (this.promiseState === 'pending') {
            this.callbacks.push({
                onReject: function () {
                    changeState('onReject');
                },
                onResolve: function () {
                    changeState('onResolve');
                }
            })

        }
    })

}

Promise.prototype.catch = function(reject){
    return this.then(null,reject);
}